import logging
from typing import Any

from aiogram import types
from aiogram_dialog import DialogManager
from arq import ArqRedis
from fluentogram import TranslatorRunner

from src.presentation.tg_bot.states import ChangeProxySG

logger = logging.getLogger(__name__)


async def set_order_id(call: types.CallbackQuery, widget: Any, manager: DialogManager, order_id: str):
    manager.dialog_data["order_id"] = order_id
    await manager.switch_to(ChangeProxySG.proxies_list)


async def set_proxy_id(call: types.CallbackQuery, widget: Any, manager: DialogManager, proxy_id: str):
    manager.dialog_data["proxy_id"] = proxy_id
    await manager.switch_to(ChangeProxySG.select_proxy)


async def set_new_proxy_id(call: types.CallbackQuery, _, manager: DialogManager, new_proxy_id: str):
    manager.dialog_data["new_proxy_id"] = new_proxy_id
    await manager.switch_to(ChangeProxySG.confirm)


async def confirm_changes(call: types.CallbackQuery, _, manager: DialogManager):
    arqredis: ArqRedis = manager.middleware_data.get("arqredis")
    locale: TranslatorRunner = manager.middleware_data.get("locale")
    order_id: int = manager.dialog_data.get("order_id")
    new_proxy_id: int = manager.dialog_data.get("new_proxy_id")

    try:
        await arqredis.enqueue_job(
            "change_proxy",
            locale=locale,
            user_id=call.from_user.id,
            order_id=order_id,
            proxy_id=manager.dialog_data.get("proxy_id"),
            new_proxy_id=new_proxy_id,
        )

        logger.info(f"Добавлена задача по смене прокси в заказе №{order_id}")

        await arqredis.enqueue_job(
            "check_proxy_speed_job",
            locale=locale,
            user_id=call.from_user.id,
            new_proxy_id=manager.dialog_data.get("new_proxy_id"),
        )

        logger.info(f"Добавлена задача по проверке скорости прокси №{new_proxy_id}")

        await call.message.answer(locale.get("in-work-msg"))
    except Exception as e:
        logger.exception(e)
        await call.message.answer(locale.get("error-msg"))
    await manager.done()
